package com.rt.tmpt.security.handler;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.rt.tmpt.dto.A2UserDto;
import com.rt.tmpt.dto.Result;
import com.rt.tmpt.service.ISecurityV2Service;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;

@Api(tags = "Security控制类")
@Controller
@Slf4j
public class SecurityAction {
	public static final String SESSION_KEY = "session_key_image_code";

	@Resource
	private ISecurityV2Service securityV2Service;

	@Autowired
	DefaultKaptcha defaultKaptcha;

	@RequestMapping(value = "/")
	public String login(){
		return "index";
	}




	@PostMapping("/meToSession")
	@ResponseBody
	public Result meToSession(Authentication authentication, HttpServletRequest request) {
		Result result = new Result();
		HttpSession session = request.getSession();

		UserDetails userDetails = (UserDetails) authentication.getPrincipal();
		String username = userDetails.getUsername();
		A2UserDto empDto = securityV2Service.getUserByLoginname(username);

		session.setAttribute("userId", empDto.getId());
		session.setAttribute("username", username);
		session.setAttribute("userFullName", empDto.getName());
		session.setAttribute("email", empDto.getEmail());
		session.setAttribute("companyId", empDto.getCompanyId());
		session.setAttribute("magSystemDtoSession", empDto);

		/*System.out.println("info me");
		if(authentication!=null) {
			System.out.println(authentication.getPrincipal());
			System.out.println("----------");
			System.out.println(authentication.getDetails());
		}*/
		return result.success();
	}


	@PostMapping("/meFromSession")
	@ResponseBody
	public Result meFromSession(Authentication authentication, HttpServletRequest request) {
		Result result = new Result();
		HttpSession session = request.getSession();

		Long userId = (Long)session.getAttribute("userId");
		String username = (String)session.getAttribute("username");
		String userFullName = (String)session.getAttribute("userFullName");
		String email = (String)session.getAttribute("email");
		Long companyId = (Long)session.getAttribute("companyId");

		result.getMap().put("userId",userId);
		result.getMap().put("username",username);
		result.getMap().put("userFullName",userFullName);
		result.getMap().put("email",email);
		result.getMap().put("companyId",companyId);
		return result.success();
	}



	@RequestMapping("/codeImage")
	public void codeImage(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse) throws Exception{
		byte[] captchaChallengeAsJpeg = null;
		ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
		try {
			//生产验证码字符串并保存到session中
			String createText = defaultKaptcha.createText();
			httpServletRequest.getSession().setAttribute(SESSION_KEY, createText);
			//使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
			BufferedImage challenge = defaultKaptcha.createImage(createText);
			ImageIO.write(challenge, "jpg", jpegOutputStream);
		} catch (IllegalArgumentException e) {
			httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
			return;
		}

		//定义response输出类型为image/jpeg类型，使用response输出流输出图片的byte数组
		captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
		httpServletResponse.setHeader("Cache-Control", "no-store");
		httpServletResponse.setHeader("Pragma", "no-cache");
		httpServletResponse.setDateHeader("Expires", 0);
		httpServletResponse.setContentType("image/jpeg");
		ServletOutputStream responseOutputStream =
				httpServletResponse.getOutputStream();
		responseOutputStream.write(captchaChallengeAsJpeg);
		responseOutputStream.flush();
		responseOutputStream.close();
	}


}
